const xml2js = require("xml2js");
const constants = require("../../data/constants");
const log4js = require('../../data/log');
const sipUtils = require("../../utils/sipUtils");
const logger = log4js.getLogger('sip');

/**
 * 查询设备信息信令
 */
module.exports={
    generate(deviceInfo) {
        if (!deviceInfo.deviceid) {
            logger.warn('设备未注册成功', deviceInfo);
            return null;
        }
        let callId = Math.round((new Date()).getTime() / 1000) + '';
        let SN = Math.round((new Date()).getTime() / 1000);
        const json = {
            Query: {
                CmdType: 'DeviceInfo',
                SN: SN,
                DeviceID: deviceInfo.deviceid
            }
        };
        const builder = new xml2js.Builder({
            xmldec: {
                'version': '1.0',
                'encoding': 'GB2312',
                'standalone': null
            }
        });
        const content = builder.buildObject(json) + '\r\n\r\n';

        let cseq = {};
        cseq.method = 'MESSAGE';
        cseq.seq = 20;

        let from = {
            name: undefined,
            uri: 'sip:' + constants.sip.option.sip_command_account + '@' + constants.sip.option.server_realm,
            params: {tag: constants.rstring()}
        };
        let to = {
            name: undefined,
            uri: 'sip:' + deviceInfo.deviceid + '@' + constants.sip.option.server_realm
        };
        let uri = sipUtils.generateUri(deviceInfo.deviceid, null, null, deviceInfo.sip_command_host, deviceInfo.sip_command_port);

        // 这里需要保存到数据库
        if (!deviceInfo.protocol) {
            deviceInfo.protocol = 'UDP';
        }

        let via = sipUtils.generateVia(deviceInfo.protocol);
        return {
            method: 'MESSAGE',
            uri,
            version: constants.sip.version,
            headers: {
                via, from, to, cseq, content,
                'call-id': callId,
                'Content-Type': 'Application/MANSCDP+xml',
                'expires': '3600',
                'Max-Forwards': 70,
                'User-Agent': constants.sip.useragent
            }
        };
    },
}
